// noinspection JSUnresolvedFunction

import {defineStore} from "pinia";
import {request_account} from "~/utils/common/request.js";
import router from "~/utils/router";
import {Cookies} from "quasar";

export const useAccountStore = defineStore('account', {
  persist: {
    enabled: true,
  },
  state: () => {
    return {
      // 用户信息
      userinfo: '',
      // 用户权限
      permissions: {},
      // 用户角色
      roles: {}, // tokens
      has_add_router: false, // 是否添加路由信息
      menu_list: [], // 菜单列表
    }
  },
  actions: {
    // 登录
    login(data) {
      return new Promise((resolve, reject) => {
        request_account.post('/api/v1.0/account/login/', data).then(resp => {
          const res_data = resp.data.data
          this.setUserInfo(res_data)
          // 跳转到上个页面
          const next = router.currentRoute.value.query.next
          const next_path = !!next ? next : '/home'
          router.push({path: next_path}).then(() => {
            resolve(resp)
          })
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 登出
    logout(refresh) {
      return new Promise((resolve, reject) => {
        return request_account.post('/api/v1.0/account/logout/', {
          refresh
        }).then(res => {
          Cookies.set('access', '')
          this.clear()
          router.push({name: 'login'}).then()
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 刷新token
    async refreshToken(refresh) {
      return await new Promise((resolve, reject) => {
        request_account.post(
          '/api/v1.0/account/token/refresh/',
          {refresh}
        ).then(res => {
          const res_data = res.data
          this.setAccess(res_data.access)
          this.setUserInfo(res_data)
          resolve(res)
        }).catch(err => {
          router.push({name: 'login'}).then()
          reject(err)
        })
      })
    },
    // 设置token
    setAccess(access) {
      Cookies.set('access', access, {expires: 1})
      Cookies.set('access_half', access, {expires: 1 / 24})
    },
    // 清除登录信息
    clear() {
      this.userinfo = ''
      this.permissions = {}
      this.roles = {}
      this.has_add_router = false
    },
    // 设置用户信息
    setUserInfo(data) {
      this.userinfo = data.userinfo
      this.permissions = data.permissions
      this.roles = data.roles
    }
  },
  getters: {
    getAccess() {
      return Cookies.get('access')
    },
    getRefresh() {
      return Cookies.get('refresh')
    },
    getPermission() {
      return (permission_id) => {
        return this.permissions[permission_id]
      }
    }
  }
})

